<script setup>
import _ from 'lodash';
import {useCommonStore} from "@jzl/stores";
import {api} from "@jzl/api";
import {onMounted, ref, watch} from "vue";
import {DFT_ICONS} from "@jzl/icons";

const DEFAULT_FORM = {
  parent_id: -1,
  icon: { icon: '', image: '', color: ''},
  type: 2,
  user_type: 1,
  group_code: '',
  group_name: '',
  group_desc: '',
  app_detail: '',
  url: '',
  ttys: [1, 2, 3]
}

const emit = defineEmits(['success', 'cancel'])
const props = defineProps({
  actionType: {
    type: String,
    default: 'view'
  }, // actionType: 'view',     // createGroup | createMenu | edit | view
  currentData: Object,
  parentGroupId: null,
  dirs: {
    type: Array,
    default: null
  }
})

const loading = ref(false)
const form = ref(_.cloneDeep(DEFAULT_FORM))
const appDirs = ref([])

onMounted(() => {
  init();

  if(!props.dirs?.length) {
    loadAppGroups();
  } else {
    appDirs.value = props.dirs;
  }
})

watch(() => [props.actionType, props.currentData], () => {
  init()
}, {deep: true})

const loadAppGroups = async () => {
  let groups = await api.menu.getGroupTree(0);

  appDirs.value = _.filter(groups, g => g.type === 3);
}

const init = () => {
  let iForm = null;

  if (props.actionType === 'createApp') {
    iForm = _.defaults({
      project_id: useCommonStore().project?.project_id,
      parent_id: props.parentGroupId || _.get(props.currentData, 'group_id', -1),
      group_name: '',
      group_code: geneNewAppCode(),
      group_desc: '',
      tty: 123
    }, DEFAULT_FORM);
  } else {
    iForm = _.cloneDeep(props.currentData);

    if (!iForm.icon) {
      iForm.icon = { icon: '', color: '', image: ''};
    } else if (_.isString(iForm.icon)) {
      iForm.icon = { icon: iForm.icon, color: '', image: ''};
    }

    if(!iForm.icon.icon && iForm.icon.iconfont) {
      iForm.icon.icon = iForm.icon.iconfont;
    }

    if (iForm.tty) {
      iForm.ttys = _.filter(_.map(`${iForm.tty}`.split(""), it => it && Number(it)), it => it);
    } else {
      iForm.ttys = [];
    }
  }

  form.value = iForm;
}

const geneNewAppCode = () => {
  let prefix = $utils.getNanoid(1, 'LCHAR');
  let code = $utils.getNanoid(3, 'LCHARNUM');

  return `${prefix}${code}`;
}

const handleSubmitCreateGroup = async () => {

  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'group_id');
  let ret = null;

  if (!data.group_code) {
    data.group_code = geneNewAppCode();
  }

  if (data.ttys) {
    data.tty = _.join(_.sortBy(data.ttys), "");
  }

  if (!data.tty) data.tty = 0;

  if (id) {
    ret = await api.group.updateGroup(id, data);
  } else {
    if (!/^[a-z][a-z\d]{0,4}$/.test(data.group_code)) {
      $jui.toast("应用编码最多5位英文小写或数字，且第一位必须是英文小写！");
      return;
    }
    ret = await api.group.createGroup(data);
  }

  let tid = _.get(form.value, 'tid') || `g_${_.get(ret, 'group_id')}` || `g_${_.get(ret, 'content_group_id')}`;

  loading.value = false;
  $jui.toast('操作成功！');
  emit('success', tid);
  // this.refreshCurrentNode(tid);
}

const handleCancelEdit = () => {
  // props.actionType = 'view';
  emit('cancel');
}
</script>

<template>
  <el-form
    v-if="form"
    ref="formRef"
    label-width="100px"
  >
    <el-form-item label="应用分类">
      <el-select
        v-model="form.parent_id"
        placeholder="请选择应用分别"
        :disabled="actionType === 'view'"
      >
        <el-option
          :key="-1"
          label=""
          :value="-1"
        />
        <el-option
          v-for="item in appDirs"
          :key="item.group_id"
          :label="item.group_name"
          :value="item.group_id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="应用名称">
      <el-input
        v-model="form.group_name"
        placeholder="名称，如：年度考核"
        :disabled="actionType === 'view'"
      />
    </el-form-item>
    <el-form-item label="应用图标">
      <div
        class="icons flex items-center"
      >
        <IconPicker
          v-model="form.icon.icon"
          :is-view="actionType === 'view'"
          class="mr-2"
        />
        <el-color-picker
          v-model="form.icon.color"
          :disabled="actionType === 'view'"
        />
        <!--<file-picker v-model="form.icon.image" theme="mini" :is-view="actionType == 'view'"></file-picker>-->
      </div>
    </el-form-item>
    <el-form-item label="应用编码">
      <el-input
        v-model="form.group_code"
        placeholder="编码，如：product"
        :disabled="actionType === 'view' || actionType === 'edit'"
      ></el-input>
    </el-form-item>
    <el-form-item label="适用终端">
      <el-checkbox-group v-model="form.ttys" size="mini" :disabled="actionType === 'view'">
        <el-checkbox-button :label="1" v-tippy="{ arrow: true }" content="管理端">
          <JIcon
            :icon="DFT_ICONS.mgr"
            style="font-size:12px;margin-right:5px;"/>
          MGR
        </el-checkbox-button>
        <el-checkbox-button :label="2" v-tippy="{ arrow: true }" content="手机端">
          <JIcon
            :icon="DFT_ICONS.h5"
            style="font-size:12px;margin-right:5px;"/>
          H5
        </el-checkbox-button>
        <el-checkbox-button :label="3" v-tippy="{ arrow: true }" content="PC端">
          <JIcon
            :icon="DFT_ICONS.pc"
            style="font-size:12px;margin-right:5px;"/>
          Web
        </el-checkbox-button>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item label="用户模式">
      <el-radio-group
        v-model="form.user_type"
        :disabled="actionType === 'view' || actionType === 'edit'"><!-- || actionType == 'edit' -->
        <el-radio
          :label="1"
          v-tippy
          content="显示所有共享用户，新增的为平台用户"
        >共享平台用户
        </el-radio>
        <el-radio
          :label="2"
          v-tippy
          content="仅显示独立用户，新增的为应用内用户"
        >应用独立用户
        </el-radio>
        <el-radio
          :label="3"
          v-tippy
          content="显示所有共享和独有用户，新增的为独有用户"
        >共享+独立用户
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="页面地址">
      <el-input
        v-model="form.url"
        placeholder="页面地址，如：/system/"
        :disabled="actionType === 'view'"
      />
    </el-form-item>
    <el-form-item label="简述/标签">
      <el-input
        type="textarea"
        :rows="2"
        v-model="form.group_desc"
        :disabled="actionType === 'view'"
      ></el-input>
    </el-form-item>
    <el-form-item label="详细描述">
      <!--<el-input type="textarea" :rows="2" v-model="form.app_detail" :disabled="actionType == 'view'"></el-input>-->
      <TinyEditor
        v-model="form.app_detail"
        ref="editor"
        :disabled="actionType === 'view'"
      ></TinyEditor>
    </el-form-item>
    <el-form-item
      label-width="0px"
      class="form-item-center"
      label="" v-if="actionType !== 'view'"
    >
      <el-button
        size="large"
        type="primary"
        @click="handleSubmitCreateGroup()"> 提交
      </el-button>
      <el-button
        size="large"
        @click="handleCancelEdit()"> 取消
      </el-button>
    </el-form-item>
  </el-form>
</template>
